package com.uxsino.simo.indicator.retractor;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.uxsino.simo.networkentity.EntityInfo;
import com.uxsino.simo.query.QueryContext;
import com.uxsino.simo.query.QueryTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class JSONArrayValueRetractor extends ListValueRetractor {

    private static Logger logger = LoggerFactory.getLogger(JSONArrayValueRetractor.class);

    @Override
    public Object doRetract(EntityInfo entity, QueryContext ctxt, QueryTemplate qt, Object obj) {

        JSONArray array = (JSONArray) obj;

        ArrayList<Map<String, Object>> records = new ArrayList<Map<String, Object>>();

        for (Object object : array) {

            Map<String, Object> temp = new HashMap<String, Object>();

            JSONObject json = (JSONObject) object;

            for (ColumnEntry entry : columnEntries) {

                Object value = json.get(entry.index);

                if (value != null) {

                    value = entry.retractor.retract(entity, ctxt, qt, value);

                } else {
                    logger.warn("column index out of range:{} . value is null!", entry.index);
                }

                temp.put(entry.field.getName(), value);
            }

            records.add(temp);
        }

        return records;
    }

}
